<template>
  <div class="breadcrumb-container" v-if="route.path !== '/'">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item v-for="(item, index) in breadcrumbItems" :key="index" @click.native="navigateTo(item.path)">
        <span :class="{ 'current': isCurrentPath(item.path) }">{{ item.title }}</span>
      </el-breadcrumb-item>
    </el-breadcrumb>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, onUnmounted } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { pageTitles, subMenuTitles } from '../utils/breadcrumbConfig';

const router = useRouter();
const route = useRoute();
const breadcrumbItems = ref([]);

// 处理子菜单选择事件
const handleSubMenuSelect = (event) => {
  const { path, index } = event.detail;
  if (path && index !== undefined) {
    const mainPath = path.replace('/', '');
    const subTitle = subMenuTitles[mainPath]?.[index];
    
    if (subTitle) {
      // 确保当前路径与传递的path一致时才更新面包屑
      if (route.path === path) {
        // 初始化面包屑，包含首页和当前页面
        resetBreadcrumb(path, pageTitles[path] || '未知页面');
        
        // 添加子页面到面包屑
        breadcrumbItems.value.push({
          path: `${path}?sub=${index}`,
          title: subTitle
        });
        
        // 保存面包屑历史
        saveBreadcrumbHistory();
      }
    }
  }
};

// 重置面包屑到二级页面
const resetBreadcrumb = (path, title) => {
  breadcrumbItems.value = [
    {
      path: '/',
      title: '首页'
    },
    {
      path,
      title
    }
  ];
};

// 添加面包屑记录
const addBreadcrumbItem = (path, title) => {
  if (path === '/') {
    breadcrumbItems.value = []; // 在主页时清空面包屑
    return;
  }

  // 如果是二级页面，重置面包屑
  if (path.split('/').length === 2 && !path.includes('?')) {
    resetBreadcrumb(path, title);
    
    // 处理URL中的查询参数
    if (route.query.sub !== undefined) {
      const mainPath = path.replace('/', '');
      const subIndex = Number(route.query.sub);
      const subTitle = subMenuTitles[mainPath]?.[subIndex];
      
      if (subTitle) {
        breadcrumbItems.value.push({
          path: `${path}?sub=${subIndex}`,
          title: subTitle
        });
      }
    }
  }
  
  // 保存面包屑历史
  saveBreadcrumbHistory();
};

// 保存面包屑历史到本地存储
const saveBreadcrumbHistory = () => {
  // 限制面包屑最多三级
  if (breadcrumbItems.value.length > 3) {
    breadcrumbItems.value = breadcrumbItems.value.slice(0, 3);
  }
  localStorage.setItem('breadcrumbHistory', JSON.stringify(breadcrumbItems.value));
};

// 导航到指定路径
const navigateTo = (path) => {
  if (path.includes('?sub=')) {
    const [basePath, subParam] = path.split('?');
    const subIndex = subParam.split('=')[1];
    router.push({ path: basePath, query: { sub: subIndex } });
  } else {
    router.push(path);
  }
};

// 检查是否是当前路径
const isCurrentPath = (path) => {
  if (path.includes('?sub=')) {
    const [basePath, subParam] = path.split('?');
    const subIndex = subParam.split('=')[1];
    return route.path === basePath && route.query.sub === subIndex;
  }
  return route.path === path;
};

// 监听路由变化
watch(() => route.fullPath, (newPath) => {
  const title = pageTitles[route.path] || '未知页面';
  addBreadcrumbItem(route.path, title);
});

// 组件挂载时加载历史记录
onMounted(() => {
  // 从本地存储加载面包屑历史
  const savedHistory = localStorage.getItem('breadcrumbHistory');
  if (savedHistory) {
    try {
      const parsed = JSON.parse(savedHistory);
      if (Array.isArray(parsed)) {
        breadcrumbItems.value = parsed;
      }
    } catch (e) {
      console.error('Failed to parse breadcrumb history:', e);
    }
  }

  // 如果当前不是首页，更新面包屑
  if (route.path !== '/') {
    const title = pageTitles[route.path] || '未知页面';
    addBreadcrumbItem(route.path, title);
  }

  // 添加子菜单选择事件监听
  window.addEventListener('setSubMenuIndex', handleSubMenuSelect);
});

// 组件卸载时移除事件监听
onUnmounted(() => {
  window.removeEventListener('setSubMenuIndex', handleSubMenuSelect);
});

// 导出组件的方法供外部使用
defineExpose({
  addBreadcrumbItem,
  navigateTo,
  isCurrentPath
});
</script>

<style scoped>
.breadcrumb-container {
  width: 1200px;
  height: 50px;
  margin: 0 auto;
  background-color: #fff;
  border-radius: 4px;
  display: flex;
  align-items: center;
  padding: 0 20px;
  box-sizing: border-box;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

:deep(.el-breadcrumb) {
  font-size: 14px;
  line-height: 50px;
}

:deep(.el-breadcrumb__item) {
  cursor: pointer;
}

:deep(.el-breadcrumb__inner) {
  color: #606266;
  transition: color 0.3s;
}

:deep(.el-breadcrumb__inner:hover) {
  color: #409EFF;
  text-decoration: underline;
}

.current {
  color: #409EFF;
  font-weight: bold;
}
</style>